package cn.apestar.modules.image.service;

import cn.apestar.common.config.Global;
import cn.apestar.common.exception.BaseException;
import cn.apestar.common.image.ImageThumb;
import cn.apestar.common.model.SMap;
import cn.apestar.common.service.BaseService;
import com.qiniu.api.auth.AuthException;
import com.qiniu.api.auth.digest.Mac;
import com.qiniu.api.io.IoApi;
import com.qiniu.api.io.PutExtra;
import com.qiniu.api.io.PutRet;
import com.qiniu.api.rs.GetPolicy;
import com.qiniu.api.rs.PutPolicy;
import com.qiniu.api.rs.URLUtils;
import org.apache.commons.codec.EncoderException;
import org.json.JSONException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文档管理
 * @author lvh
 */
@Service
@Transactional(readOnly = true)
public class ImageService extends BaseService {

    final String[] allpict = new String[] {".jpg" , ".jpeg" , ".gif" , ".jpeg" , ".png" , ".bmp" , ".JPG" , ".JPGE" , ".GIF" , ".JPEG" , ".PNG" ,
            ".BMP"};

    /**
     * 图片上传
     * @param file
     * @return
     * @throws IOException
     */
    public Map deploy(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
        // 得到所有的文件：
        List fileItems;
        String message = "";
        // 生成当前时间 的
        PrintWriter out = response.getWriter();
        Map map = new HashMap();
        String c_pname = "";
        String spath = "";
        int it = 1;
        String a = request.getParameter("a");
        Iterator<String> iter = request.getFileNames();
        while (iter.hasNext()) {
            // 记录上传过程起始时的时间，用来计算上传时间
            int pre = (int) System.currentTimeMillis();
            // 取得上传文件
            MultipartFile file = request.getFile(iter.next());
            if (file != null) {
                map = uloadFile(file, out, it, c_pname, spath);
            }
        }
        map.put("a", a);
        return map;
        // out.println("<script>uploadOK(" + a + ",'"+spath+"','"+c_pname+"');</script>");
    }

    /**
     * 图片上传
     * @param file
     * @return
     * @throws IOException
     * @throws JSONException
     * @throws AuthException
     * @throws EncoderException
     */
    public Map deployQN(MultipartHttpServletRequest request, HttpServletResponse response)
        throws IOException, AuthException, JSONException, EncoderException {
        // 得到所有的文件：

        Map map = new HashMap();
        Mac mac = new Mac(Global.getConfig("qiniu_access_key"), Global.getConfig("qiniu_secret_key"));
        // 请确保该bucket已经存在
        PutPolicy putPolicy = new PutPolicy(Global.getConfig("qiniu_bucket_name"));
        String uptoken = putPolicy.token(mac);
        PutExtra extra = new PutExtra();
        Iterator<String> iter = request.getFileNames();
        String a = request.getParameter("a");
        while (iter.hasNext()) {
            MultipartFile file = request.getFile(iter.next());
            if (file != null) {
                String key = System.currentTimeMillis() + file.getName();
                PutRet ret = IoApi.Put(uptoken, key, file.getInputStream(), extra);
                String url = getQiniuFileUrl(Global.getConfig("qiniu_domain"), ret.getKey());
                map = new SMap("name", key, "spath", url, "path", url);
            }
        }
        map.put("a", a);
        return map;
    }

    /**
     * 下载七牛云
     * @return
     * @throws EncoderException
     * @throws AuthException
     */
    public String getQiniuFileUrl(String demain, String key) throws EncoderException, AuthException {
        Mac mac = new Mac(Global.getConfig("qiniu_access_key"), Global.getConfig("qiniu_secret_key"));
        String baseUrl = URLUtils.makeBaseUrl(demain, key);
        GetPolicy getPolicy = new GetPolicy();
        String downloadUrl = getPolicy.makeRequest(baseUrl, mac);
        // downloadUrl = URLEncoder.encode(downloadUrl);
        return downloadUrl;
    }

    /**
     * 保存图片
     * @param file
     * @param out
     * @param it
     * @param c_pname
     * @param spath
     */
    public Map uloadFile(MultipartFile file, PrintWriter out, int it, String c_pname, String spath) {
        final int MAX_SIZE = Global.getMaxImage() * Global.getMaxSize();// 设置上传文件最大为 300k
        String name = file.getOriginalFilename();
        long size = file.getSize();
        String path;
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmssS");
        String tday = formater.format(new Date());
        // 是否图片
        String tnam = name.substring(name.lastIndexOf("."), name.length());
        boolean picge = false;

        for (String sin : allpict) {
            if (tnam.equals(sin)) {
                picge = true;
            }
        }

        if (!picge) {
            throw new BaseException("不是图片格式");
        } else {
            if (size > MAX_SIZE) {
                // System.out.println("2");
                throw new BaseException("上传图片太大");
            }

            it++;
            path = Global.getProjectImagePath() + "pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/" + tday + it + tnam;
            String savpath = Global.getProjectImagePath() + "pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/thumb_" + tday + it + tnam;

            // 获得图片名
            c_pname = tday + it + tnam;
            File file1 = new File(path);

            spath = "/pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/thumb_" + tday + it + tnam;
            boolean b = file1.getParentFile().isDirectory();
            if (!b) {
                file1.getParentFile().mkdirs();// 创建目录
            }
            try {
                // 写入图片
                file.transferTo(file1);
                // 缩略图
                float p = 170;
                ImageThumb.toZipJpg(path, savpath, 170);

            } catch (Exception e) {
                System.out.println(e.getMessage());
                out.println("<script>uploadErr();</script>");
            }
        }

        return new SMap("name", c_pname, "spath", spath, "path", path);
    }

    /**
     * 保存图片
     * @param file
     * @param out
     * @param it
     * @param c_pname
     * @param spath
     */
    public Map uloadFileCar(MultipartFile file, PrintWriter out, int it, String c_pname, String spath) {
        final int MAX_SIZE = Global.getMaxImage() * Global.getMaxSize();// 设置上传文件最大为 300k
        String name = file.getOriginalFilename();
        long size = file.getSize();
        String path;
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmmssS");
        String tday = formater.format(new Date());
        // 是否图片
        String tnam = name.substring(name.lastIndexOf("."), name.length());
        boolean picge = false;

        for (String sin : allpict) {
            if (tnam.equals(sin)) {
                picge = true;
            }
        }

        if (!picge) {
            throw new BaseException("不是图片格式");
        } else {
            if (size > MAX_SIZE) {
                // System.out.println("2");
                throw new BaseException("上传图片太大");
            }

            it++;
            path = Global.getProjectImagePath() + "pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/" + tday + it + tnam;
            String savpath = Global.getProjectImagePath() + "pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/thumb_" + tday + it + tnam;

            // 获得图片名
            c_pname = tday + it + tnam;
            File file1 = new File(path);

            spath = "/pic/" + tday.substring(0, 6) + "/" + tday.substring(6, 8) + "/thumb_" + tday + it + tnam;
            boolean b = file1.getParentFile().isDirectory();
            if (!b) {
                file1.getParentFile().mkdirs();// 创建目录
            }
            try {
                // 写入图片
                file.transferTo(file1);

            } catch (Exception e) {
                System.out.println(e.getMessage());
                out.println("<script>uploadErr();</script>");
            }
        }

        return new SMap("name", c_pname, "spath", spath, "path", path);
    }

}
